#define _REENTRANT

#include <stdio.h>
#include <unistd.h>
#include "sthread.h"
#include "sync.h"

static sthread_sem_t *g_sem;
static int g_var;

int threadmain(void* arg) {
	int n_thread = (int) arg;
	printf("thread %d: Trying to change g_var\n", n_thread);
	printf("thread %d: g_var = %d\n", n_thread, g_var);
	//if (sthread_sem_try_down(g_sem) == 0){
		sthread_sem_down(g_sem);
		++g_var;
		printf("thread %d: Inside Semaphore - g_var = %d\n", n_thread, g_var);
		sthread_sem_up(g_sem);
	//}
	/*else {
		printf("thread %d: sem_try_down failed\n", n_thread);
	}*/
	return 0;
}

int main(int argc, char* argv[]) {
	g_sem = (sthread_sem_t*) malloc(sizeof(sthread_sem_t));
	sthread_sem_init(g_sem, 1);
	g_var = 0;

	sthread_t thr1, thr2;
	sthread_init();

	sthread_create(&thr1, threadmain, (void*)1);
	sthread_create(&thr2, threadmain, (void*)2);
	
	sthread_sem_destroy(g_sem);

	free(g_sem);
	
	return 0;
}